﻿using CefSharp;
using CefSharp.SchemeHandler;
using CefSharp.WinForms;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace ThirdApp
{
    public partial class FrmMain : Form
    {
        private ChromiumWebBrowser chromeBrowser;


        public FrmMain()
        {
            InitializeComponent();
            InitializeChromium();
        }
        public void InitializeChromium()
        {


            string indexpage = string.Format(@"{0}\html\html\index.html", Application.StartupPath);
            if (!File.Exists(indexpage))
            {
                MessageBox.Show("程序将要退出，本地网页文件不错在：" + indexpage);
                return;
            }

            CefSettings settings = new CefSettings();

            //Example of setting a command line argument
            //Enables WebRTC
            settings.CefCommandLineArgs.Add("enable-media-stream", "1");

            settings.CefCommandLineArgs.Add("no-proxy-server", "1");
            settings.CefCommandLineArgs.Add("proxy-server", "ProxyAddress");
            settings.CachePath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "CefSharp\\Cache");

            Cef.Initialize(settings, performDependencyCheck: true, browserProcessHandler: null);

            chromeBrowser = new ChromiumWebBrowser(indexpage);
            toolStripContainer1.ContentPanel.Controls.Add(chromeBrowser);
            chromeBrowser.Dock = DockStyle.Fill;

            BrowserSettings browserSettings = new BrowserSettings();
            browserSettings.FileAccessFromFileUrls = CefState.Enabled;
            browserSettings.UniversalAccessFromFileUrls = CefState.Enabled;
            chromeBrowser.BrowserSettings = browserSettings;

            CefSharpSettings.LegacyJavascriptBindingEnabled = true;
            //在浏览器中注册一个javascript对象
            //BingdingOptions:Cefsharp版本必须大于63，否则会报错
            chromeBrowser.RegisterJsObject("cefCustomObject", new CefCustomObject(chromeBrowser, this));
        }

        private void Form1_FormClosing(object sender, FormClosingEventArgs e)
        {
            Cef.Shutdown();
        }

        /// <summary>
        /// 打开调试工具
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnOpenDebugTool_Click(object sender, EventArgs e)
        {
            chromeBrowser.ShowDevTools();
        }
    }
}
